package at.falb.games.alcatraz.api.common;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PropertiesReader {

	private static Logger logger = Logger.getLogger(PropertiesReader.class.getName());
    private static String readError = "Read of server names from properties file is failed.";

	private static File configFile;

    public PropertiesReader(String file) {
    	configFile = new File(file);
    }

    public String[] getServerNames() {
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (configFile);
            doc.getDocumentElement().normalize();
            NodeList listOfServers = doc.getElementsByTagName("server");
            String[] loginServers = new String[listOfServers.getLength()];
            for(int ix = 0; ix < listOfServers.getLength() ; ix++){
                Node firstPersonNode = listOfServers.item(ix);
                if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                    Element loginServer = (Element)firstPersonNode;
                    NodeList nameList = loginServer.getElementsByTagName("name");
                    Element serverNameElement = (Element)nameList.item(0);
                    NodeList textFNList = serverNameElement.getChildNodes();
                    String strLoginServer = ((Node)textFNList.item(0)).getNodeValue().trim();
                    NodeList portList = loginServer.getElementsByTagName("port");
                    Element serverPortElement = (Element)portList.item(0);
                    NodeList textLNList = serverPortElement.getChildNodes();
                    strLoginServer += ":"+((Node)textLNList.item(0)).getNodeValue().trim();
                    loginServers[ix] = strLoginServer;
                }
            }
            return loginServers;
        } catch (IOException exc) {
        	logger.log(Level.SEVERE, readError, exc);
        } catch (ParserConfigurationException exc) {
        	logger.log(Level.SEVERE, readError, exc);
		} catch (SAXException exc) {
        	logger.log(Level.SEVERE, readError, exc);
		}
    	return null;
    }
}
